import axios from 'axios';
import { useRouter } from 'vue-router';
import { API_CONFIG } from '../config/apiConfig';

const router = useRouter();

// 创建axios实例
const request = axios.create({
  baseURL: API_CONFIG.BASE_URL,
  withCredentials: true,
  timeout: 10000
});

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data;
    // 检查返回码
    if (res.code === "0001") {
      // 清理用户数据
      localStorage.removeItem('userInfo');
      document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
      
      // 跳转登录页
      router.push('/');
      
      return Promise.reject(new Error('Session expired'));
    }
    return res;
  },
  error => {
    return Promise.reject(error);
  }
);

export default request;